<?php

namespace addons\yungift\controller;


use addons\yungift\library\Logic;
use addons\yungift\model\Activity;
use addons\yungift\model\Config;

/**
 * 公共接口
 */
class Common extends BaseApi
{
    public $noNeedLogin = ['getConfig', 'getActivityList'];

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取配置
     */
    public function getConfig()
    {
        $baseConfig = Config::getGroupAttributes(Config::GROUP_BASE);
        $data = [];
        $loginMethods = $baseConfig['login_methods'] ?? '';
        $data['login_methods'] = $loginMethods ? explode(',', $loginMethods) : [];
        $data['login_note'] = $baseConfig['login_note'] ?? '注：仅内部使用，请选择合适的方式登录进行礼品兑换。';
        $data['select_activity'] = (int)($baseConfig['select_activity'] ?? 0);
        $data['default_activity'] = Activity::where([
            'is_default' => Activity::DEFAULT_YES,
            'status'     => Activity::STATUS_NORMAL
        ])->find() ? 1 : 0;  // 存在默认活动
        $data['welcome_countdown'] = 5;  // 5秒倒计时
        $data['mp_login'] = (int)Config::getGroupAttribute(Config::GROUP_MP, 'mp_login', 0);;

        $disableOptions = $baseConfig['disable_options'] ?? '';
        $data['disable_options'] = $disableOptions ? explode(',', $disableOptions) : [];

        if ($activity = Activity::getCurrent($this->memberData)) {
            $data['activity_id'] = $activity->id;
            $data['welcome_img'] = $activity->welcome_img ? cdnurl($activity->welcome_img, true) : '';
            $data['login_top_img'] = $activity->login_top_img ? cdnurl($activity->login_top_img, true) : '';
            $data['home_top_img'] = $activity->home_top_img ? cdnurl($activity->home_top_img, true) : '';
            $data['activity_img'] = $activity->activity_img ? cdnurl($activity->activity_img, true) : '';
            $data['activity_rich'] = $activity->activity_rich ?? '';
            if ($activity->login_methods) {
                $data['login_methods'] = explode(',', $activity->login_methods);
            }
            if ($activity->login_note) {
                $data['login_note'] = $activity->login_note;
            }
            $data['tips'] = $activity->tips;
        } else {
            if (input('get.activity_id')) {
                $data['activity_invalid'] = 1;  // 告诉前端当前活动无效
            }
        }

        $this->success(__('成功'), $data);
    }

    /**
     * 获取活动列表
     */
    public function getActivityList()
    {
        $group = $this->request->post('group');
        if (! (int)(Config::getGroupAttribute(Config::GROUP_BASE, 'select_activity') ?? 0)) {
            $this->error('没有开启活动列表的显示功能');
        }

        // 数据列表
        $query = Activity::where(['status' => Activity::STATUS_NORMAL])
            ->order('weight DESC, id DESC');

        if ($group === 'ing') {
            $query->where('start_time', '<=', time())->where('end_time', '>', time());
        } elseif ($group === 'end') {
            $query->where('end_time', '<=', time());
        }
        $result = $query->paginate($this->request->post('page_size', 10), false);
        $result = Logic::getPageData($result, [
            'id',
            'name',
            'cover_url',
            'start_time',
            'end_time',
            'state',
            'join' => function ($item) {
                return 0;
            }
        ]);

        $this->success(__('成功'), $result);
    }

    /**
     * 上传图片
     */
    public function uploadImage()
    {
        if (! $file = $this->request->file('image')) {
            $this->error('图片没有上传成功');
        }
        $suffix = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
        if (in_array($file->getInfo('type'),
                ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp'])
            || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
            $imgInfo = getimagesize($file->getInfo('tmp_name'));
            if (! $imgInfo || ! isset($imgInfo[0]) || ! isset($imgInfo[1])) {
                $this->error('只允许上传图片');
            }
        } else {
            $this->error('只允许上传图片');
        }
        if (! $file->checkSize(1024 * 1024 * 5)) {
            $this->error('只允许上传小于5M的图片');
        }
        if (! $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'yungift')) {
            $this->error($file->getError());
        }

        $filePath = DS . 'uploads' . DS . 'yungift' . DS . $info->getSaveName();
        $this->success(__('成功'), ['path' => $filePath, 'url' => cdnurl($filePath, true)]);
    }
}
